package com.achao.usercenter.controller;

import cn.hutool.core.bean.BeanUtil;
import com.achao.usercenter.annotation.LogIgnore;
import com.achao.usercenter.annotation.enums.LogIgnoreEnum;
import com.achao.usercenter.common.BaseCommon;
import com.achao.usercenter.req.UserSearchReq;
import com.achao.usercenter.utils.ThrowUtils;
import com.achao.usercenter.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.achao.usercenter.common.BaseResp;
import com.achao.usercenter.common.ErrorCode;
import com.achao.usercenter.common.ResultUtils;
import com.achao.usercenter.exception.BusinessException;
import com.achao.usercenter.entity.User;
import com.achao.usercenter.req.UserLoginReq;
import com.achao.usercenter.resp.UserRegisterReq;
import com.achao.usercenter.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.achao.usercenter.contant.UserConstant.ADMIN_ROLE;
import static com.achao.usercenter.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @param userRegisterReq
     * @return
     */
    @PostMapping("/register")
    public BaseResp<Long> userRegister(@RequestBody UserRegisterReq userRegisterReq) {
        // 校验
        ThrowUtils.throwIf(userRegisterReq == null,new BusinessException(ErrorCode.PARAMS_ERROR));
        String userAccount = userRegisterReq.getUserAccount();
        String userPassword = userRegisterReq.getUserPassword();
        String checkPassword = userRegisterReq.getCheckPassword();
        String planetCode = System.currentTimeMillis() + "";
        long result = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginReq
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResp<User> userLogin(@RequestBody UserLoginReq userLoginReq,
                                    @LogIgnore HttpServletRequest request) {
        if (userLoginReq == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginReq.getUserAccount();
        String userPassword = userLoginReq.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResp<Integer> userLogout(@LogIgnore HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResp<User> getCurrentUser(@LogIgnore HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    @GetMapping("/search")
    public BaseResp<List<UserVO>> searchUsers(UserSearchReq req,
                                              @LogIgnore HttpServletRequest request) {
        List<UserVO> userVOS = new ArrayList<>();
        Map<String, Object> resMap = new HashMap<>();
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }

        String username = req.getUsername();
        String userAccount = req.getUserAccount();
        Integer gender = req.getGender();
        String phone = req.getPhone();
        String email = req.getEmail();
        String userStatus = req.getUserStatus();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        if (StringUtils.isNotBlank(userAccount)) {
            queryWrapper.like("account", userAccount);
        }
        if (StringUtils.isNotBlank(userStatus)) {
            queryWrapper.like("status", userStatus);
        }
        if (StringUtils.isNotBlank(email)) {
            queryWrapper.like("email", email);
        }
        if (StringUtils.isNotBlank(phone)) {
            queryWrapper.like("phone", phone);
        }
        if (gender != null) {
            queryWrapper.eq("gender", gender);
        }

        queryWrapper.orderByAsc("create_time");
        Page<User> userPage = new Page<>(req.getPageNO(), req.getPageSize());
        Page<User> page = userService.page(userPage, queryWrapper);
        userVOS = page.getRecords().stream().map(user -> BeanUtil.copyProperties(user, UserVO.class)).collect(Collectors.toList());
        resMap.put(BaseCommon.SUCCESS, Boolean.TRUE);
        resMap.put(BaseCommon.TOTAL, page.getTotal());
        return ResultUtils.success(userVOS,resMap);
    }

    @PostMapping("/delete")
    public BaseResp<Boolean> deleteUser(@RequestBody long id,
                                        @LogIgnore HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    private boolean isAdmin(@LogIgnore HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }

}
